package com.wuwangfu.transfor;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.IterativeStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author jcshen
 * @Date 2023-02-23
 * @PackageName:com.wuwangfu.transfor
 * @ClassName: IterateTransf
 * @Description:
 * @Version 1.0.0
 *
 * Iterate迭代流式计算，分布式for循环
 *
 * https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/datastream/operators/overview/#iterate
 */
public class IterateTransf {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> line = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Long> nums = line.map(Long::parseLong);
        /**
         * 调用iterate方法 DataStream -> IterativeStream
         * 对nums进行迭代（不停的输入int的数字）
         */
        IterativeStream<Long> iterate = nums.iterate();
        /**
         * IterativeStream -> DataStream
         * 对迭代出来的数据进行运算，对输入的数据应用更新模型，即输入数据处理逻辑
         */
        SingleOutputStreamOperator<Long> maped = iterate.map(new MapFunction<Long, Long>() {
            @Override
            public Long map(Long value) throws Exception {
                System.out.println("iterate input =>" + value);
                return value -= 2;
            }
        });
        //只要满足value >0 的条件，就会形成一个回路，重新迭代，即将前面的输出作为输入，再进行一次应用更新模型
        SingleOutputStreamOperator<Long> feedback = maped.filter(new FilterFunction<Long>() {
            @Override
            public boolean filter(Long value) throws Exception {
                return value > 0;
            }
        });
        //传入迭代的条件
        iterate.closeWith(feedback);
        //不满足迭代条件的最后要输出
        SingleOutputStreamOperator<Long> output = maped.filter(new FilterFunction<Long>() {
            @Override
            public boolean filter(Long value) throws Exception {
                return value <= 0;
            }
        });

        //数据结果
        output.print("output value:");


        env.execute();

    }
}
